﻿
using Edu.Application.Interfaces;
using Edu.Application.Model.RequestModel;
using Edu.Domain;
using Edu.Domain.Model;
using EStart.DataBase.EF;
using EStart.DataBase.Event.Domian;
using EStart.Infrastructure.ClientData;
using QuestionBank.Infrastructure.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Edu.Application.Model.Messaging;
using Edu.Application.Model.ResponseModel;
using EStart.Infrastructure.Domain;
using Microsoft.EntityFrameworkCore;
using EStart.Infrastructure.Extensions;
using Edu.Application.Extensions;
using Edu.Application.Model.Models;

namespace Edu.Application.Implements
{
    public class RoleGroupService : ServiceCore<RoleGroup>, IRoleGroupService
    {

        public RoleGroupService(
            EduDbContext context,
            EventDbContext eventDbContext
            ) : base(context, eventDbContext)
        {
        }

        public ApiResult<string> Delete(Guid guid)
        {
            ApiResult<string> response = new ApiResult<string>();
            try
            {

                var school = Query().Where(n => n.Guid == guid).FirstOrDefault();
                if (school == null)
                {
                    response.message = "未找到改数据！";
                    return response;
                }
                DeleteForge(school);
                var b = _unitofwork.Commit();
                response.success = b;
                response.message = b ? "删除成功！" : "删除失败！";
                return response;
            }
            catch (Exception ex)
            {
                response.message = "删除失败！意外错误:" + ex.Message;
                return response;
            }
        }

        public async Task<ApiResult<List<CheckModel>>> GetCheckModelAsync()
        {
            ApiResult<List<CheckModel>> response = new ApiResult<List<CheckModel>>();
            try
            {

                var check = await Query().Select(n => new CheckModel
                {
                    label = n.Name,
                    value = n.ID
                }).ToListAsync();
                response.success = true;
                response.data = check;
                response.message = "获取成功！";
                return response;
            }
            catch (Exception ex)
            {
                response.message = "获取失败！意外错误:" + ex.Message;
                return response;
            }
        }

        public ApiResult<RoleGroupModel> GetDetail(Guid guid)
        {
            ApiResult<RoleGroupModel> response = new ApiResult<RoleGroupModel>();
            try
            {

                var entity = Query().Where(n => n.Guid == guid)
                    .Select(n => new RoleGroupModel
                    {
                        CreateTime = n.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        RoleDataLevel = n.RoleDataLevel,
                        guid = n.Guid.ToString(),
                        Name = n.Name,
                        Remark = n.Remark,
                        Role = n.RoleAndRoleGroup.Select(c => c.RoleID).ToList()
                    }).FirstOrDefault();
                if (entity == null)
                {
                    response.message = "未找到改数据！";
                    return response;
                }
                response.success = true;
                response.data = entity;
                response.message = "获取成功！";
                return response;
            }
            catch (Exception ex)
            {
                response.message = "获取失败！意外错误:" + ex.Message;
                return response;
            }
        }

        public async Task<ApiResult<Page<RoleGroupModel>>> GetPagesAsync(RoleGroupPage request)
        {
            ApiResult<Page<RoleGroupModel>> response = new ApiResult<Page<RoleGroupModel>>();
            try
            {
                var pages = await Query()
                            .HasWhere(request.RoleGroupName, n => n.Name.Contains(request.RoleGroupName))
                            .Select(n => new RoleGroupModel
                            {
                                CreateTime = n.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                RoleDataLevel = n.RoleDataLevel,
                                guid = n.Guid.ToString(),
                                Name = n.Name,
                                Remark = n.Remark
                            }).OrderByDescending(n => n.CreateTime).ToPageAsync(request.PageIndex, request.PageSize);

                response.success = true;
                response.message = "获取成功！";
                response.data = pages;
                return response;

            }
            catch (Exception ex)
            {
                response.message = "获取失败！意外错误：" + ex.Message;
                return response;
            }
        }



        public async Task<ApiResult<string>> SaveAsync(RoleGroupModel request)
        {
            ApiResult<string> response = new ApiResult<string>();
            try
            {
                if (string.IsNullOrEmpty(request.guid))
                {

                    RoleGroup model = new RoleGroup();
                    model.Remark = request.Remark;
                    model.RoleDataLevel = request.RoleDataLevel;
                    model.Name = request.Name;
                    model.RoleAndRoleGroup = new List<RoleInRoleGroup>();

                    if (request.Role != null)
                    {

                        //新增不存在的
                        foreach (var item in request.Role)
                        {

                            model.RoleAndRoleGroup.Add(new RoleInRoleGroup()
                            {
                                RoleGroupID = model.ID,
                                RoleID = item
                            });

                        }
                     

                    }   await _unitofwork.RegisterNewAsync(model);
                }
                else
                {
                    var sguid = Guid.Parse(request.guid);
                    var old = Query().Include(n => n.RoleAndRoleGroup).Where(n => n.Guid == sguid).FirstOrDefault();
                    if (old == null)
                    {
                        throw new Exception("未找到修改数据！！");
                    }

                    old.Name = request.Name;
                    old.Remark = request.Remark;
                    old.RoleDataLevel = request.RoleDataLevel;
                    if (old.RoleAndRoleGroup == null)
                    {
                        old.RoleAndRoleGroup = new List<RoleInRoleGroup>();
                    }
                    if (request.Role != null)
                    {
                        //新增不存在的
                        foreach (var item in request.Role)
                        {
                            var role = old.RoleAndRoleGroup.Where(n => n.RoleID == item).FirstOrDefault();
                            if (role == null)
                            {
                                await _unitofwork.RegisterNewAsync(new RoleInRoleGroup()
                                {
                                    RoleGroupID = old.ID,
                                    RoleID = item
                                });

                            }
                        }
                        //删除移除的
                        foreach (var item in old.RoleAndRoleGroup)
                        {
                            var delrole = request.Role.Where(n => n == item.RoleID).Count();
                            if (delrole == 0)
                            {
                                _unitofwork.RegisterDeleted(item);
                            }
                        }

                    }
                    _unitofwork.RegisterDirty(old);

                }

                var b = await _unitofwork.CommitAsync();

                response.success = b;
                response.message = b ? "保存成功！" : "保存失败";
                return response;
            }
            catch (Exception ex)
            {

                response.message = "发生错误：" + ex.Message;
                return response;
            }
        }
    }
}
